import py_trees
import random
import time


class speekEnglish(py_trees.behaviour.Behaviour):
    def __init__(self, name, time):
        super().__init__(name)
        self.name = name
        self.time = time

    def update(self):
        start_time = time.time()
        print(f"{self.name} speek ...")
        time.sleep(self.time)

        duration_time = time.time() - start_time
        print(f"{self.name} speek end ------ {round(duration_time, 2)}")
        return py_trees.common.Status.SUCCESS


class speekChinese(py_trees.behaviour.Behaviour):
    def __init__(self, name, time):
        super().__init__(name)
        self.name = name
        self.time = time

    def update(self):
        start_time = time.time()
        print(f"{self.name} 说中文 ...")
        time.sleep(self.time)

        duration_time = time.time() - start_time
        print(f"{self.name} 说中文 end ------ {round(duration_time, 2)}")
        return py_trees.common.Status.SUCCESS


def create_behavior_tree():
    # 创建并行节点：
    # 策略1: SuccessOnAll() - 所有子节点成功才返回成功
    # 策略2: SuccessOnOne() - 任一子节点成功就返回成功
    root = py_trees.composites.Parallel(
        name="并行", policy=py_trees.common.ParallelPolicy.SuccessOnAll()
    )
    # 创建行为
    speek_english = speekEnglish(name="speek_english", time=2)
    speek_chinese = speekChinese(name="speek_chinese", time=3)

    # 添加到并行节点
    root.add_children([speek_english, speek_chinese])
    return root


def main():
    # 创建行为树
    behavior_tree = create_behavior_tree()
    # 打印树结构
    print("行为树结构:")
    print(py_trees.display.ascii_tree(behavior_tree))

    # 运行行为树
    start_time = time.time()
    while True:
        behavior_tree.tick_once()  # 每次只执行一次
        if behavior_tree.status == py_trees.common.Status.SUCCESS:
            break
        print("------------------>")

    duration_time = time.time() - start_time
    print(f"行为树运行结束 ------ {round(duration_time, 2)}")


if __name__ == "__main__":
    main()
